<?php
namespace Core\Application;

use Core\Debugger\AlertLevel;
use Core\Debugger\LogEntry;
use \Core\Debugger\Logger;

/**
 * Configuration settings
 * @namespace Core\Application
 * @author Raphael DE FREITAS (RaphyTheGeek@gmail.com]
 * @version 1.0
 *
 */
final class Configuration
{
	/**
	 * Contains all configuration vars
	 * @var array
	 * @see __get
	 */
	protected $_Vars = array();
	
	/**
	 * Contains a instance of the Configuration class
	 * @var\Core\Application\Configuration
	 */
	protected static $_Instance = null;
	
	/**
	 * Initializes a new instance of the Configuration class
	 */
	private function __construct() {
		
	}
	
	/**
	 * Get the value of the configuration variable specified
	 * @param string $name Variable name
	 * @return string Value of the specified variable if variable exists otherwise null
	 */
	public function __get($name) {
		if(isset($this->_Vars[$name]))
			return $this->_Vars[$name];
		else
			return null;
	}
	
	/**
	 * Set the specified value to the specified variable
	 * @param string $name Varialbe name
	 * @param string $value Variable value
	 * @throws \DomainException
	 */
	public function __set($name, $value) {
		throw new  \DomainException("Properties can't be overwrited");
	}
	
	/**
	 * Get the instance of the Configuration class
	 * @return Configuration The instance of the Configuration class
	 */
	public static function getInstance() {
		if(is_null(self::$_Instance))
			self::$_Instance = new Configuration;
		return self::$_Instance;
	}
	
	/**
	 * Load variables from the configuration file specified
	 * @param string $file Path of the configuration file
	 */
	public function addFromFile($file) {
		Logger::log(new LogEntry('Reading configuration file '.str_replace(ROOT, './', $file).'...'));
		$xml = new \DOMDocument;
		$xml->load($file);
		$vars = $xml->getElementsByTagName('var');
		foreach($vars as $var) {
			if(isset($this->_Vars[$var->getAttribute('name')]))
				Logger::log(new LogEntry("Configuration file $file overwrite the variable ".$var->getAttribute('name'), AlertLevel::Warning));
			if ($var->hasAttribute('name') && $var->hasAttribute('value') && !isset($this->_Vars[$var->getAttribute('name')]))
				$this->_Vars[$var->getAttribute('name')] = $var->getAttribute('value');
		}
	}
}
?>